package com.example.onlinemonitoring.comCenter;

import com.alibaba.druid.sql.ast.statement.SQLIfStatement.Else;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.*;
import com.example.onlinemonitoring.model.DataFile.DataFileHeader;
import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.serviceImpl.DljfsensorServiceImpl;
import org.springframework.context.annotation.Scope;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

@Service("dljfCom")
@Scope("prototype")
public class DljfCom extends CommPortManager {
    private int Vertype = 1;
    private String PointName = "新监测点";
    private int PointCount = 1;
    private int DeviceCount = 1;
    int iGispdSend =0;
    int iXYGispdSend =0;
    int ibackup =0;
    int MqttAddr = 0;
    MqttMessage mqttMessage;
    DataFileHeader dataFileHeader = new DataFileHeader();
    //float MqttDischargeAmount =0;
    //int MqttDischargecount =0;
    //float  MqttDischargePhase = 0;
    Lock lck = new ReentrantLock();
    @Autowired
    private DljfsensorServiceImpl dljfsensorService;

    @Override
    public void receiveData(String str) {
        int status = 0;
        int LastAlarmLevel = 0;
        String LastAlarmMessage = "0";
        int addr = Integer.parseInt(str.substring(2, 4), 16);
        reSend[addr] = 0;
        str = str.toUpperCase();// 将字符串转换成大号
        setText(str);
        // if(str.length() != 44) return;|| (!str.substring(4, 6).equals("81"))
        int minadd = 10;
        if ((!str.substring(0, 2).equals("7F")) && (!str.substring(0, 2).equals("7C")))
            return;
        int num = 0;
        float dischargeratio = 1;
        Dljfsensor dljf = new Dljfsensor();
        dljf.setStationid(ad.getStationid());
        dljf.setDevicegroup(ad.getDevicegroup());
        dljf.setDeviceaddr(addr);
        // Dljfsensor record = dljfsensorService.getModel(dljf);
        MyResult<Dljfsensor> res = dljfsensorService.getList(dljf);
        setText("电缆局放设备返回数据： 站点号：1 设备地址" + addr);
        // String stlyestr = record.getStyle();
        Integer startIndex = 12;
        String currentPath = System.getProperty("user.dir");
        Random ran = new Random();
        if (str.substring(0, 2).equals("7F")) {
            Vertype = 2;
            MqttAddr = addr;
           // if(MqttAddr==1)
          //  dataFileHeader.DeleteAll(currentPath + "//rixindljf//");
            num = res.getCount();
            for (int i = 0; i < num; i++) {
                Dljfsensor record = res.getData().get(i);
                if (record == null) {
                    setText("当前数据库无监测点：设备地址" + addr + "的监测点" + i + 1 + " ！ 请先添加该监测点！");
                    return;
                }

                if (record.getInuse() == 0)
                    continue;
                dischargeratio = record.getCurrentcoefficientvalue() == null ? 1f : record.getCurrentcoefficientvalue();
                float dischargecoefficientvalue = record.getCurrentcoefficientvalue() == null ? 1f
                        : record.getCurrentcoefficientvalue();
                // Random ran=new Random();
                float fadischarge = parseHex88(str.substring(startIndex, startIndex += 2)) * dischargecoefficientvalue
                        / 10;
                //dljf.setLastadischarge(fadischarge); // A相放电量
                if (fadischarge != 0)
                    dljf.setLastaphase((int) (ran.nextFloat() * 360));
                else
                    dljf.setLastaphase(0);
                int  areq = parseHex4(str.substring(startIndex, startIndex += 2));
               // dljf.setLastareq(parseHex4(str.substring(startIndex, startIndex += 2)));// A相放电频次
                // float fbdischarge = parseHex88(str.substring(startIndex, startIndex += 2)) *
                // dischargecoefficientvalue / 10;
                // dljf.setLastbdischarge(fbdischarge);

                if(ad.getBrand().equals("MQTT"))
                {

                    String MqttfileAddr = "zjrxDLJF" + ((MqttAddr-1)*PointCount + i + 1)+"_";
                    dataFileHeader.Deletefile(MqttfileAddr,currentPath + "//rixindljf//");
                   // String currentPath = System.getProperty("user.dir");
                   // MqttdataFile(dataFileHeader.readFileToMqttMessage(currentPath + "//pds3.txt"));
                   if (mqttMessage != null) {
                    MqttdataFile(MqttAddr, (i + 1),mqttMessage);
                    dljf.setLastadischarge(dataFileHeader.getDischargeSignalPeak());
                    dljf.setLastareq(dataFileHeader.getDischargecount());
                    dljf.setLastaphase((int)dataFileHeader.getDischargePhase());
                } else {
                    MqttdataFile(MqttAddr,(i + 1),dataFileHeader.readFileToMqttMessage(currentPath + "//pds3.txt"));
                    dljf.setLastadischarge(dataFileHeader.getDischargeSignalPeak());
                    dljf.setLastareq(dataFileHeader.getDischargecount());
                    dljf.setLastaphase((int)dataFileHeader.getDischargePhase());
                }
                }
                else{
                    dljf.setLastadischarge(fadischarge); // A相放电量
                    dljf.setLastareq(parseHex4(str.substring(startIndex, startIndex += 2)));// A相放电频次
                }
                
                setText("放电量：" + dljf.getLastadischarge() + "pC 放电频次：" + dljf.getLastareq() + " 相位："
                        + dljf.getLastaphase() + "度 监测点:" + (i + 1));

                dljf.setPointaddr(record.getPointaddr());
                SensorData(record, dljf);
            }
        } else if (str.substring(0, 2).equals("7C") && (str.length() == 40)) {
            minadd = 12;
            Vertype = 1;
            // if((stlyestr==null)||(stlyestr.equals("")))
            // {
            // stlyestr="adischarge|1|A相放电量,bdischarge|1|B相放电量,cdischarge|1|C相放电量,aphase|1|A相相位,bphase|1|B相相位,cphase|1|C相相位,areq|1|A相放电频次,breq|1|B相放电频次,creq|1|C相放电频次,a1discharge|1|A1相放电量,b1discharge|1|B1相放电量,c1discharge|1|C1相放电量,a1phase|1|A1相相位,b1phase|1|B1相相位,c1phase|1|C1相相位,a1req|1|A1相放电频次,b1req|1|B1相放电频次,c1req|1|C1相放电频次";
            // record.setStyle(stlyestr);
            // }
            dljf.setLastadischarge(parseHex88(str.substring(minadd, minadd += 2)) * dischargeratio / 10); // A相放电量
            dljf.setLastaphase((int) (ran.nextFloat() * 360));
            dljf.setLastareq(parseHex4(str.substring(minadd, minadd += 2)));// A相放电频次
            dljf.setLastbdischarge(parseHex88(str.substring(minadd, minadd += 2)) * dischargeratio / 10);
            ;// B 相放电量
            dljf.setLastbphase((int) (ran.nextFloat() * 360));
            dljf.setLastbreq(parseHex4(str.substring(minadd, minadd += 2)));// b相放电频次
            dljf.setLastcdischarge(parseHex88(str.substring(minadd, minadd += 2)) * dischargeratio / 10);
            ;// c相放电量
            dljf.setLastcphase((int) (ran.nextFloat() * 360));
            dljf.setLastcreq(parseHex4(str.substring(minadd, minadd += 2)));// c相放电频次
            dljf.setLasta1discharge(parseHex88(str.substring(minadd, minadd += 2)) * dischargeratio / 10); // A1相放电量
            dljf.setLasta1phase((int) (ran.nextFloat() * 360));
            dljf.setLasta1req(parseHex4(str.substring(minadd, minadd += 2)));// A相放电频次
            dljf.setLastb1discharge(parseHex88(str.substring(minadd, minadd += 2)) * dischargeratio / 10);
            ;// B1 相放电量
            dljf.setLastb1phase((int) (ran.nextFloat() * 360));
            dljf.setLastb1req(parseHex4(str.substring(minadd, minadd += 2)));// b相放电频次
            dljf.setLastc1discharge(parseHex88(str.substring(minadd, minadd += 2)) * dischargeratio / 10);
            ;// c1相放电量
            dljf.setLastc1phase((int) (ran.nextFloat() * 360));
            dljf.setLastc1req(parseHex4(str.substring(minadd, minadd += 2)));// c相放电频次
            setText("A相放电量：" + dljf.getLastadischarge() + "pC A相放电频次：" + dljf.getLastareq() + " A相相位："
                    + dljf.getLastaphase() + "度");
            setText("B相放电量：" + dljf.getLastbdischarge() + "pC B相放电频次：" + dljf.getLastbreq() + " B相相位："
                    + dljf.getLastbphase() + "度");
            setText("C相放电量：" + dljf.getLastcdischarge() + "pC C相放电频次：" + dljf.getLastcreq() + " C相相位："
                    + dljf.getLastcphase() + "度");
            setText("A1相放电量：" + dljf.getLasta1discharge() + "pC A1相放电频次：" + dljf.getLasta1req() + " A1相相位："
                    + dljf.getLasta1phase() + "度");
            setText("B1相放电量：" + dljf.getLastb1discharge() + "pC B1相放电频次：" + dljf.getLastb1req() + " B1相相位："
                    + dljf.getLastb1phase() + "度");
            setText("C1相放电量：" + dljf.getLastc1discharge() + "pC C1相放电频次：" + dljf.getLastc1req() + " C1相相位："
                    + dljf.getLastc1phase() + "度");
        } else
            return;

        addrindex++;
    }

    private void SensorData(Dljfsensor dljf, Dljfsensor dljfsensor) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        if (dljf.getAdischargealarmvalue() == null ||
                dljf.getAdischargealarmrelievevalue() == null ||
                dljf.getAdischargewarnvalue() == null ||
                dljf.getAdischargewarnrelievevalue() == null /*
                                                              * ||
                                                              * dljf.getAreqwarnvalue() == null||
                                                              * dljf.getAreqwarnrelievevalue() == null ||
                                                              * dljf.getAreqalarmrelievevalue() == null ||
                                                              * dljf.getAreqalarmvalue() == null ||
                                                              * dljf.getAphasealarmvalue() == null ||
                                                              * dljf.getAphasealarmrelievevalue() == null ||
                                                              * dljf.getAphasewarnvalue() == null ||
                                                              * dljf.getAphasewarnrelievevalue() == null
                                                              */
        ) {
            setText("设备地址" + dljf.getDeviceaddr() + " 未设置报警值！");
            return;
        }
        List<Integer> array = new ArrayList<>();
        dljfsensor.setLastadischargealarmstatus(
                GetAlarmStatus(isnull(dljfsensor.getLastadischarge()), isnull(dljf.getAdischargealarmvalue()),
                        isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                        isnull(dljf.getAdischargewarnrelievevalue()),
                        isnull(dljf.getLastadischargealarmstatus()), true, "放电量", dljf.getDevicegroup(),
                        dljf.getDeviceaddr(), dljf.getPointname(), dljf.getPointaddr()));
        alarmMessage += GetAlarmMessage(dljfsensor.getLastadischargealarmstatus(), "放电量");
        array.add(dljfsensor.getLastadischargealarmstatus());
        // dljfsensor.setLastbdischargealarmstatus(
        // GetAlarmStatus(isnull(dljfsensor.getLastbdischarge()),
        // isnull(dljf.getAdischargealarmvalue()),
        // isnull(dljf.getAdischargealarmrelievevalue()),
        // isnull(dljf.getAdischargewarnvalue()),
        // isnull(dljf.getAdischargewarnrelievevalue()),
        // isnull(dljf.getLastbdischargealarmstatus()), true, "B相放电量",
        // dljf.getDevicegroup(),
        // dljf.getDeviceaddr(), dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastbdischargealarmstatus(),
        // "B相放电量");
        // array.add(dljfsensor.getLastbdischargealarmstatus());
        // dljfsensor.setLastcdischargealarmstatus(
        // GetAlarmStatus(isnull(dljfsensor.getLastcdischarge()),
        // isnull(dljf.getAdischargealarmvalue()),
        // isnull(dljf.getAdischargealarmrelievevalue()),
        // isnull(dljf.getAdischargewarnvalue()),
        // isnull(dljf.getAdischargewarnrelievevalue()),
        // isnull(dljf.getLastcdischargealarmstatus()), true, "C相放电量",
        // dljf.getDevicegroup(),
        // dljf.getDeviceaddr(), dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(),
        // "C相放电量");
        // array.add(dljfsensor.getLastcdischargealarmstatus());
        // dljfsensor.setLastareqalarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastareq()),
        // isnull(dljf.getAreqalarmvalue()),
        // isnull(dljf.getAreqalarmrelievevalue()), isnull(dljf.getAreqwarnvalue()),
        // isnull(dljf.getAreqwarnrelievevalue()),
        // isnull(dljf.getLastareqalarmstatus()), true,"A相放电频次",dljf.getDeviceaddr(),
        // dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(),
        // "A相放电频次");
        // array.add(dljfsensor.getLastcdischargealarmstatus());
        // dljfsensor.setLastbreqalarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastbreq()),
        // isnull(dljf.getAreqalarmvalue()),
        // isnull(dljf.getAreqalarmrelievevalue()),
        // isnull(dljfsensor.getAreqwarnvalue()),
        // isnull(dljf.getAreqwarnrelievevalue()),
        // isnull(dljf.getLastbreqalarmstatus()), true,"B相放电频次",dljf.getDeviceaddr(),
        // dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(),
        // "B相放电频次");
        // array.add(dljfsensor.getLastcdischargealarmstatus());
        // dljfsensor.setLastcreqalarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastcreq()),
        // isnull(dljf.getAreqalarmvalue()),
        // isnull(dljf.getAreqalarmrelievevalue()), isnull(dljf.getAreqwarnvalue()),
        // isnull(dljf.getAreqwarnrelievevalue()),
        // isnull(dljf.getLastcreqalarmstatus()), true,"C相放电频次",dljf.getDeviceaddr(),
        // dljf.getPointname()));
        // alarmMessage += GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(),
        // "C相放电频次");
        // array.add(dljfsensor.getLastcdischargealarmstatus());
        if (Vertype == 1) {
            dljfsensor.setLasta1dischargealarmstatus(
                    GetAlarmStatus(isnull(dljfsensor.getLasta1discharge()), isnull(dljf.getAdischargealarmvalue()),
                            isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                            isnull(dljf.getAdischargewarnrelievevalue()),
                            isnull(dljf.getLasta1dischargealarmstatus()), true, "A1相放电量", dljf.getDevicegroup(),
                            dljf.getDeviceaddr(), dljf.getPointname()));
            alarmMessage += GetAlarmMessage(dljfsensor.getLasta1dischargealarmstatus(), "A1相放电量");
            array.add(dljfsensor.getLasta1dischargealarmstatus());
            dljfsensor.setLastb1dischargealarmstatus(
                    GetAlarmStatus(isnull(dljfsensor.getLastb1discharge()), isnull(dljf.getAdischargealarmvalue()),
                            isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                            isnull(dljf.getAdischargewarnrelievevalue()),
                            isnull(dljf.getLastb1dischargealarmstatus()), true, "B1相放电量", dljf.getDevicegroup(),
                            dljf.getDeviceaddr(), dljf.getPointname()));
            alarmMessage += GetAlarmMessage(dljfsensor.getLastb1dischargealarmstatus(), "B1相放电量");
            array.add(dljfsensor.getLastb1dischargealarmstatus());
            dljfsensor.setLastc1dischargealarmstatus(
                    GetAlarmStatus(isnull(dljfsensor.getLastc1discharge()), isnull(dljf.getAdischargealarmvalue()),
                            isnull(dljf.getAdischargealarmrelievevalue()), isnull(dljf.getAdischargewarnvalue()),
                            isnull(dljf.getAdischargewarnrelievevalue()),
                            isnull(dljf.getLastc1dischargealarmstatus()), true, "C1相放电量", dljf.getDevicegroup(),
                            dljf.getDeviceaddr(), dljf.getPointname()));
            alarmMessage += GetAlarmMessage(dljfsensor.getLastc1dischargealarmstatus(), "C1相放电量");
            array.add(dljfsensor.getLastc1dischargealarmstatus());
            // dljfsensor.setLasta1reqalarmstatus(GetAlarmStatus(isnull(dljfsensor.getLasta1req()),
            // isnull(dljf.getAreqalarmvalue()),
            // isnull(dljf.getAreqalarmrelievevalue()), isnull(dljf.getAreqwarnvalue()),
            // isnull(dljf.getAreqwarnrelievevalue()),
            // isnull(dljf.getLasta1reqalarmstatus()), true,"A1相放电频次",dljf.getDeviceaddr(),
            // dljf.getPointname()));
            // alarmMessage += GetAlarmMessage(dljfsensor.getLasta1reqalarmstatus(),
            // "A1相放电频次");
            // array.add(dljfsensor.getLasta1reqalarmstatus());
            // dljfsensor.setLastb1reqalarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastb1req()),
            // isnull(dljf.getAreqalarmvalue()),
            // isnull(dljf.getAreqalarmrelievevalue()),
            // isnull(dljfsensor.getAreqwarnvalue()),
            // isnull(dljf.getAreqwarnrelievevalue()),
            // isnull(dljf.getLastb1reqalarmstatus()), true,"B1相放电频次",dljf.getDeviceaddr(),
            // dljf.getPointname()));
            // alarmMessage += GetAlarmMessage(dljfsensor.getLastb1reqalarmstatus(),
            // "B1相放电频次");
            // array.add(dljfsensor.getLastb1reqalarmstatus());
            // dljfsensor.setLastc1reqalarmstatus(GetAlarmStatus(isnull(dljfsensor.getLastc1req()),
            // isnull(dljf.getAreqalarmvalue()),
            // isnull(dljf.getAreqalarmrelievevalue()), isnull(dljf.getAreqwarnvalue()),
            // isnull(dljf.getAreqwarnrelievevalue()),
            // isnull(dljf.getLastc1reqalarmstatus()), true,"C1相放电频次",dljf.getDeviceaddr(),
            // dljf.getPointname()));
            // alarmMessage += GetAlarmMessage(dljfsensor.getLastc1reqalarmstatus(),
            // "C1相放电频次");
            // array.add(dljfsensor.getLastc1reqalarmstatus());
        }

        /*
         * dljfsensor.setLastaphasealarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastaphase()), isnull(dljf.getAphasealarmvalue()),
         * isnull(dljf.getAphasealarmrelievevalue()), isnull(dljf.getAphasewarnvalue()),
         * isnull(dljf.getAphasewarnrelievevalue()),
         * isnull(dljf.getLastaphasealarmstatus()), true,"A相相位",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastbphasealarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastbphase()), isnull(dljf.getAphasealarmvalue()),
         * isnull(dljf.getAphasealarmrelievevalue()), isnull(dljf.getAphasewarnvalue()),
         * isnull(dljf.getAphasewarnrelievevalue()),
         * isnull(dljf.getLastbphasealarmstatus()), true,"B相相位",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastcphasealarmstatus(GetAlarmStatus(isnull(dljfsensor.
         * getLastcphase()), isnull(dljf.getAphasealarmvalue()),
         * isnull(dljf.getAphasealarmrelievevalue()), isnull(dljf.getAphasewarnvalue()),
         * isnull(dljf.getAphasewarnrelievevalue()),
         * isnull(dljf.getLastcphasealarmstatus()), true,"C相相位",dljf.getDeviceaddr(),
         * dljf.getPointname()));
         * 
         * dljfsensor.setLastalarmmessage(
         * GetAlarmMessage(dljfsensor.getLastadischargealarmstatus(),"A相放电量")+
         * GetAlarmMessage(dljfsensor.getLastbdischargealarmstatus(),"B相放电量")+
         * GetAlarmMessage(dljfsensor.getLastcdischargealarmstatus(),"C相放电量")
         * 
         * GetAlarmMessage(dljf.getLastareqalarmstatus(),"A相频次")+
         * GetAlarmMessage(dljf.getLastbreqalarmstatus(),"B相频次")+
         * GetAlarmMessage(dljf.getLastcreqalarmstatus(),"C相频次")+
         * 
         * GetAlarmMessage(dljf.getLastaphasealarmstatus(),"A相相位")+
         * GetAlarmMessage(dljf.getLastbphasealarmstatus(),"B相相位")+
         * GetAlarmMessage(dljf.getLastcphasealarmstatus(),"C相相位"));
         * int[] status_arr = {dljfsensor.getLastadischargealarmstatus(),
         * dljfsensor.getLastbdischargealarmstatus(),dljfsensor.
         * getLastcdischargealarmstatus()
         * dljfsensor.getLastareqalarmstatus(),dljfsensor.getLastbreqalarmstatus(),
         * dljfsensor.getLastcreqalarmstatus(),dljfsensor.getLastaphasealarmstatus(),
         * dljfsensor.getLastbphasealarmstatus(),
         * dljfsensor.getLastcphasealarmstatus()
         */

        alarmLevel = HexUtil.MAX(array);
        dljfsensor.setLastalarmlevel(alarmLevel);
        dljfsensor.setLastalarmmessage(alarmMessage);
        dljfsensor.setLastcommunicationstatus(0);
        dljfsensor.setLastdatatime(new Date());
        dljfsensor.setLasthisdatatime(addHistory(dljf));
        lck.lock();
        if (dljfsensorService.Update(dljfsensor, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
        lck.unlock();
    }

    private Date addHistory(Dljfsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Dljfsensor sensor) {
        Dljfhistory his = new Dljfhistory();
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setDatatime(sensor.getLastdatatime());
        his.setPointname(sensor.getPointname());
        his.setPointaddr(sensor.getPointaddr());
        his.setStationid(sensor.getStationid());
        his.setCommunicationstatus(sensor.getLastcommunicationstatus());
        // 需要添加自己定义的属性
        // 频次
        his.setAreq(sensor.getLastareq());
        // his.setBreq(sensor.getLastbreq());
        // his.setCreq(sensor.getLastcreq());

        // 相位
        his.setAphase(sensor.getLastaphase());
        // his.setBphase(sensor.getLastbphase());
        // his.setCphase(sensor.getLastcphase());

        // 放电量
        his.setAdischarge(sensor.getLastadischarge());
        // his.setBdischarge(sensor.getLastbdischarge());
        // his.setCdischarge(sensor.getLastcdischarge());

        // 报警状态

        his.setAreqalarmstatus(sensor.getLastareqalarmstatus());
        // his.setBreqalarmstatus(sensor.getLastbreqalarmstatus());
        // his.setCreqalarmstatus(sensor.getLastcreqalarmstatus());

        his.setAdischargealarmstatus(sensor.getLastadischargealarmstatus());
        // his.setBdischargealarmstatus(sensor.getLastbdischargealarmstatus());
        // his.setCdischargealarmstatus(sensor.getLastcdischargealarmstatus());
        if (Vertype == 1) {
            his.setA1req(sensor.getLasta1req());
            his.setB1req(sensor.getLastb1req());
            his.setC1req(sensor.getLastc1req());
            his.setA1phase(sensor.getLasta1phase());
            his.setB1phase(sensor.getLastb1phase());
            his.setC1phase(sensor.getLastc1phase());
            his.setA1discharge(sensor.getLasta1discharge());
            his.setB1discharge(sensor.getLastb1discharge());
            his.setC1discharge(sensor.getLastc1discharge());
            his.setA1reqalarmstatus(sensor.getLasta1reqalarmstatus());
            his.setB1reqalarmstatus(sensor.getLastb1reqalarmstatus());
            his.setC1reqalarmstatus(sensor.getLastc1reqalarmstatus());
            his.setA1dischargealarmstatus(sensor.getLasta1dischargealarmstatus());
            his.setB1dischargealarmstatus(sensor.getLastb1dischargealarmstatus());
            his.setC1dischargealarmstatus(sensor.getLastc1dischargealarmstatus());
        }

        /*
         * his.setAphasealarmstatus(sensor.getLastaphasealarmstatus());
         * his.setBphasealarmstatus(sensor.getLastbphasealarmstatus());
         * his.setCphasealarmstatus(sensor.getLastcphasealarmstatus());
         */

        dljfsensorService.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice appdevice) throws Exception {
        // 开始发送
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int timersp = (int) Math.round(appdevice.getTimersp() * 1000);

        if(ad.getBrand().equals("MQTT"))
        Mqttdate(appdevice);
       
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (dlhlVertype == 1)
                isrun = false;
            if (isrun) {
                if (addrindex > appdevice.getAddrmax() || addrindex < appdevice.getAddrmin())
                    addrindex = appdevice.getAddrmin();
                cstr = String.format(appdevice.getCmd(), String.format("%02X", addrindex));
                Send(cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                    dljfsensorService.UpdateStatus(ad, addrindex, 1);
                    reSend[addrindex] = 0;
                    addrindex++;
                }
            } else if (rescode != 0) {
                setText(resmsg[rescode]);
            }
            Thread.sleep(timersp);

        }

    }

    void Mqttdate(Appdevice appdevice)
    {
       
        String cstr = "";
        DeviceCount = appdevice.getAddrmax();
        PointCount = appdevice.getPointcount();
        //String HOST = "tcp://"+appdevice.getIp()+":1883";
        String HOST = "tcp://127.0.0.1:1883";
        String TOPIC = "/8E02000213012344/subnode/534b500d003e00590000/data_ctrl/property";
        int qos = 1;
        String clientid = "subClientdljf";
        // String userName = "admin";
        // String passWord = "123456";
        String userName = "xyjf";
        String passWord = "xyjf321";
        // host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
        // Date currenttime = new Date();
        // Long lentime =currenttime.getTime();
        // Random ran = new Random();
        // lentime+=ran.nextInt(10);
        try {

            MqttClient client = new MqttClient(HOST, clientid, new MemoryPersistence());

            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            options.setAutomaticReconnect(ON);
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(userName);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 设置回调函数
            client.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost");
                }

                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("topic:" + topic);
                    System.out.println("Qos:" + message.getQos());
                    if(topic.contains("534b500d003e00590000")==false)
                    return;
                    iXYGispdSend++;
                    mqttMessage = message;
                   // MqttdataFile(MqttAddr, message);


                    String currentPath = System.getProperty("user.dir") ;
                    if(ibackup>120)
                    {
                        dataFileHeader.DeleteAll(currentPath+"//rixindljfbackup//");   
                        ibackup = 0;                  
                    }
                    ibackup++;

                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

            });
            client.connect(options);
            setText("connect..."+TOPIC);
            // 订阅消息
            client.subscribe(TOPIC, qos);

    
            while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if (addrindex > appdevice.getAddrmax() || addrindex < appdevice.getAddrmin())
                addrindex = appdevice.getAddrmin();
                cstr = String.format(appdevice.getCmd(), String.format("%02X", addrindex));
                //cstr = cstr + CRC16.calcCrc16(cstr);
                Send(cstr);
                if (reSend[addrindex] > 3) {
                    dljfsensorService.UpdateStatus(ad, addrindex, 1);
                 reSend[addrindex] = 0;
                 addrindex++;
                }
                reSend[addrindex]++;
                iGispdSend++;
                if(iGispdSend>(600*1000/timersp))
                {
                    if(iXYGispdSend<=2)
                    {
                        setText("shutdown\r\n"); 
                        //Runtime.getRuntime().exec("shutdown -r -t 0");
                       Runtime.getRuntime().exec("sc restart ");
                       String GatewayServicePath="D:\\GatewayService_V0.3.17_20231229\\GatewayService.exe restart";
                       Runtime.getRuntime().exec(GatewayServicePath);
                       iGispdSend=0; 
                       iXYGispdSend=0;
                       //String currentPath = System.getProperty("user.dir");
                       //MqttdataFile(dataFileHeader.readFileToMqttMessage(currentPath + "//pds3.txt"));
                    }
                    else{
                        iGispdSend=0; 
                        iXYGispdSend=0;
                    }
                }
                } else if (rescode != 0) {
                setText(resmsg[rescode]);
                }
            Thread.sleep(timersp);
            }
            client.unsubscribe(TOPIC);
            client.disconnect();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();

           
        }
    }
    void MqttdataFile(int deviceaddr,int Pointaddr,MqttMessage message) {


        int sum = DeviceCount*PointCount;
        String currentPath = System.getProperty("user.dir") ;
       // dataFileHeader.DeleteAll(currentPath+"//rixindljf//");

       SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        Date currenttime = new Date();
        String formattime = sdf.format(currenttime);

        dataFileHeader.setFileGenerationTime(Long.parseLong(formattime));
        byte[] bManufacturer = new byte[32];
        String Manufacturer = String.format("%s","浙江日新电气") ;
        String Manufacturers = zerorFormat(Manufacturer,32);
        bManufacturer = Manufacturers.getBytes();
        dataFileHeader.setManufacturer(bManufacturer);
        byte[] bModel = new byte[32];
        String Model = String.format("%s","SUN-IGuard-504") ;
        String Models = zerorFormat(Model,32);
        bModel = Models.getBytes();
        dataFileHeader.setModel(bModel);
        byte[] bSerialNumber = new byte[32];
        int iSerialNumber = 1;
       // String SerialNumber = String.format("%s","S10000000000000111") ;
        //String SerialNumbers = zerorFormat(SerialNumber,32);
        //bSerialNumber = SerialNumbers.getBytes();
        //dataFileHeader.setSerialNumber(bSerialNumber);
        try {
        Random ran = new Random();
        //System.out.println("message content:"+new String(message.getPayload()));
        String msg = new String(message.getPayload());
        // JSONArray json = JSONArray.parseArray(msg);
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String id = jsonObject.getString("id");
        String version = jsonObject.getString("version");
        JSONObject params = jsonObject.getJSONObject("params");
        //JSONObject status = params.getJSONObject("status");
        //int battery = status.getIntValue("battery");
        JSONObject HFCT = params.getJSONObject("HFCT");
        // JSONObject UHF = jsonObject.getJSONObject("UHF");
        String Acqtime = HFCT.getString("Acqtime");
        int phaseWindowCount = HFCT.getIntValue("PhaseWindows");
        int amplitudeQuantization = HFCT.getIntValue("QuantizedAmplitude");
        int powerFrequencyCycleCount = HFCT.getIntValue("PowerFrequencyCycles");
        byte Unit = HFCT.getByteValue("Unit");
        float MaxLimit = HFCT.getFloatValue("MaxLimit");
        float MinLimit = HFCT.getFloatValue("MinLimit");
        byte BandWidth = HFCT.getByteValue("BandWidth");
        int AlarmLevel = HFCT.getIntValue("AlarmLevel");
        int PDType = HFCT.getIntValue("PDType");
        float Peak = HFCT.getFloatValue("Peak");
        float Average = HFCT.getFloatValue("Average");
        int DenoisingN = HFCT.getIntValue("DenoisingN");
        setText("Peak:"+Peak);
        setText("DenoisingN:"+DenoisingN);
        //if(DenoisingN>255)
        //DenoisingN=245;
        int izbound = (int)(Peak - Average);
        if(izbound>10)
        izbound=10 + ran.nextInt(3);
        if(izbound<3)
        izbound=3+ ran.nextInt(3);
        int ibound = DenoisingN/10 + 1;
        float MqttDischargeAmount = Peak + izbound ;
        if(MqttDischargeAmount>MaxLimit)
        {
            MqttDischargeAmount = MaxLimit;    
            izbound = (int)(MaxLimit - Peak);
        }
        int MqttDischargecount = 0;
        if(DenoisingN==0)
        MqttDischargecount=0;
        else
        {
            MqttDischargecount = DenoisingN + ran.nextInt(ibound);
        }
        int F50 = HFCT.getIntValue("F50");
        int F100 = HFCT.getIntValue("F100");
        JSONArray dischargeTypeProbability = HFCT.getJSONArray("PDTypeProbability");
        JSONArray PRPD = HFCT.getJSONArray("PRPD");
        JSONArray PRPS = HFCT.getJSONArray("PRPS");

        int iDT = 0,ipdt=0;
        byte[] PDTypeData = new byte[8];
        for (int i = 0; i < dischargeTypeProbability.size(); i++) {
            PDTypeData[i] = dischargeTypeProbability.getByteValue(i);
            if(iDT< PDTypeData[i])
            {
                iDT=PDTypeData[i];
                ipdt++;
            }
            }
        String DT = DischargeType[ipdt];

        byte[] PRPSData = new byte[3200];
        byte[] PRPDData = new byte[3200];
        float iDischargePhase = 0;
        float  MqttDischargePhase = 0;
        int MaxDischargeData = 0;
        int iPRPSData = 0;
        int iPRPDData = 0;
        //for (int j = 0; j < PointCount; j++) 
        {
            iSerialNumber = deviceaddr;
            String SerialNumber = String.format("%s%02d","S300000000000000",iSerialNumber) ;
            String SerialNumbers = zerorFormat(SerialNumber,32);
            bSerialNumber = SerialNumbers.getBytes();
            dataFileHeader.setSerialNumber(bSerialNumber);

            Dljfsensor dljf = new Dljfsensor();
            dljf.setStationid(ad.getStationid());
            dljf.setDevicegroup(ad.getDevicegroup());
            dljf.setDeviceaddr(deviceaddr);
            dljf.setPointaddr(Pointaddr);
            //setText("setPointaddr:"+(iSerialNumber));
            //MyResult<Dljfsensor> res = dljfsensorService.getList(dljf);
            dljf = dljfsensorService.getModel(dljf);
            //if (dljf.getInuse() == 0||dljf.getLastcommunicationstatus()>0)
             //   continue;
            //PointCount = res.getCount();
           // for (int k = 0; k < PointCount; k++) 
            //{
                                            
               // DischargeAmount = (byte)((Peak-Average + ran.nextInt(3))*DenoisingN/1);
               //MqttDischargeAmount  = Average + ran.nextInt(5); 
              // MqttDischargecount = DenoisingN + ran.nextInt(200);
                // Dljfsensor record = res.getData().get(k);
                // if (record == null) {
                //     setText("当前数据库无监测点：设备地址" + j+1 + "的监测点" + k + 1 + " ！ 请先添加该监测点！");
                //     return;
                // }
                // if (record.getInuse() == 0)
                //     continue;
                // record.setPointaddr(k+1);

            for (int i = 0; i < PRPS.size(); i++) {

                //PRPSData[i] = PRPS.getByteValue(i);
                iPRPSData = PRPS.getIntValue(i);
                if(iPRPSData<=-128)
                iPRPSData=-118;
                if(iPRPSData>=128)
                iPRPSData=118;
                ByteBuffer buffer = ByteBuffer.allocate(4);
                buffer.putInt(iPRPSData);
                PRPSData[i] =buffer.get(3);
                if(MaxDischargeData<iPRPSData)
                {
                     MaxDischargeData = iPRPSData;  
                     iDischargePhase++;                             
                }

                if (iPRPSData == MaxLimit||iPRPSData <= -10) {
                    //MqttDischargeAmount = Peak ;
                } else {
                    //PRPSData[i] -= ran.nextInt(izbound);
                    iPRPSData =  iPRPSData + ran.nextInt(izbound);
                    ByteBuffer buffer1 = ByteBuffer.allocate(4);
                    buffer1.putInt(iPRPSData);
                    PRPSData[i] =buffer1.get(3);
                }
            }
            MqttDischargePhase = (iDischargePhase%powerFrequencyCycleCount)/64*360;
            if(MqttDischargecount==0)
            MqttDischargePhase=0;
            else if(MqttDischargePhase==0){
                MqttDischargePhase = ran.nextInt(360);
            }
                for (int i = 0; i < PRPD.size(); i++) {
                    iPRPDData = PRPD.getIntValue(i);
                   // PRPDData[i] = PRPD.getByteValue(i);
                    if (iPRPDData == 0) {

                    } else {
                       // PRPDData[i] += ran.nextInt(3);
                       iPRPDData = iPRPDData + ran.nextInt(3);
                       ByteBuffer buffer = ByteBuffer.allocate(4);
                       buffer.putInt(iPRPDData);
                       PRPDData[i] =buffer.get(3);
                    }
                }
                if (dljf == null) {
                
                }else{
                    PointName = dljf.getPointname();
                   // dljf.setLastadischarge( MqttDischargeAmount);
                   // dljf.setLastdischargetype(DT);
                  // dljf.setLastareq( MqttDischargecount);
                 //  dljf.setLastaphase((int) MqttDischargePhase);
                 //  lck.lock();
                //   if (dljfsensorService.Update(dljf, false) == 0) {
                //    setText("更新实时数据失败，请检查数据库连接");
               // }
               // lck.unlock();
                }

                iPRPSData = (int)(MqttDischargeAmount) ;
                ByteBuffer buffer = ByteBuffer.allocate(4);
                buffer.putInt(iPRPSData); 
                PRPSData[ran.nextInt(3200)]  = buffer.get(3);

                byte[] bdeviceName = new byte[118];
                //String deviceNames = String.format("%114s", ad.getName()) ;  
                String deviceName = ad.getName();
                String deviceNames = zerorFormat(deviceName,118);
                bdeviceName = deviceNames.getBytes();
                byte[] bdeviceCode = new byte[42];
                String deviceCode = String.format("%d", deviceaddr);
                String deviceCodes = zerorFormat(deviceCode,42);
                bdeviceCode = deviceCodes.getBytes();
                byte[] bmeasurementPointName = new byte[128];
                //String measurementPointName = String.format("%126s", PointName) ; 
                String PointNames = PointName;
                String measurementPointName = zerorFormat(PointNames,128);  
                bmeasurementPointName = measurementPointName.getBytes();
                byte[] bmeasurementPointCode = new byte[32];
                String measurementPointCode = String.format("%d", Pointaddr);
                //String measurementPointCode = String.format("%030X\0", j + 1);
                String measurementPointCodes = zerorFormat(measurementPointCode,32);
                bmeasurementPointCode = measurementPointCodes.getBytes();

                // currenttime = new Date();
                // Long lentime =currenttime.getTime();
                // lentime+=iSerialNumber*1000;
                // currenttime.setTime(lentime);
                // formattime = sdf.format(currenttime);
        
                //nowtime = HexUtil.todate(new Date()).getTime();
                dataFileHeader.setSpectrumType1((byte)0x11);
                dataFileHeader.setSpectrumGenerationTime1(Long.parseLong(formattime));
                dataFileHeader.setDeviceName1(bdeviceName);
                dataFileHeader.setDeviceCode1(bdeviceCode);
                dataFileHeader.setMeasurementPointName1(bmeasurementPointName);
                dataFileHeader.setMeasurementPointCode1(bmeasurementPointCode);
                dataFileHeader.setDataType1((byte) 1);
                dataFileHeader.setAmplitudeUnit1(Unit);
                dataFileHeader.setAmplitudeLowerLimit1(MinLimit);
                dataFileHeader.setAmplitudeUpperLimit1(MaxLimit);
                dataFileHeader.setBandwidth1(BandWidth);
                // dataFileHeader.prpdGraph.setLowerFrequency(0.5f);
                // dataFileHeader.prpdGraph.setUpperFrequency(100);
                dataFileHeader.setPhaseWindowCount1(phaseWindowCount);
                dataFileHeader.setAmplitudeQuantization1(amplitudeQuantization);
                dataFileHeader.setPowerFrequencyCycleCount1(0);
                dataFileHeader.setDischargecount1(MqttDischargecount);
                dataFileHeader.setDischargePhase1(MqttDischargePhase);
                dataFileHeader.setDischargeTypeProbability1(PDTypeData);
                dataFileHeader.setDischargeSignalPeak1(MqttDischargeAmount);
                dataFileHeader.setDischargeSignalAverage1(Average);
                dataFileHeader.setSpectrumData1(PRPDData);
               // setText("generateprpdData:"+(j + 1));
                dataFileHeader.generateprpdData(dataFileHeader,currentPath+"//rixindljf//"+"zjrxDLJF" + ((deviceaddr-1)*PointCount + Pointaddr)+ "_MONT_SPDC1_21_" + Acqtime + ".dat");
                dataFileHeader.generateprpdData(dataFileHeader,currentPath+"//rixindljfbackup//"+"zjrxDLJF" + ((deviceaddr-1)*PointCount + Pointaddr)+ "_MONT_SPDC1_21_" + Acqtime + ".dat");
                dataFileHeader.setSpectrumType((byte)0x12);
                dataFileHeader.setSpectrumGenerationTime(Long.parseLong(formattime));
                dataFileHeader.setDeviceName(bdeviceName);
                dataFileHeader.setDeviceCode(bdeviceCode);
                dataFileHeader.setMeasurementPointName(bmeasurementPointName);
                dataFileHeader.setMeasurementPointCode(bmeasurementPointCode);
                dataFileHeader.setDataType((byte) 1);
                dataFileHeader.setAmplitudeUnit(Unit);
                dataFileHeader.setAmplitudeLowerLimit(MinLimit);
                dataFileHeader.setAmplitudeUpperLimit(MaxLimit);
                dataFileHeader.setBandwidth(BandWidth);
                // dataFileHeader.prpsGraph.setLowerFrequency(0.5f);
                // dataFileHeader.prpsGraph.setUpperFrequency(100);
                dataFileHeader.setPhaseWindowCount(phaseWindowCount);
                dataFileHeader.setAmplitudeQuantization(0);
                dataFileHeader.setPowerFrequencyCycleCount(powerFrequencyCycleCount);
                dataFileHeader.setDischargecount(MqttDischargecount);
                dataFileHeader.setDischargePhase(MqttDischargePhase);
                dataFileHeader.setDischargeTypeProbability(PDTypeData);
                dataFileHeader.setDischargeSignalPeak(MqttDischargeAmount);
                dataFileHeader.setDischargeSignalAverage(Average);
                dataFileHeader.setSpectrumData(PRPSData);
                //setText("generateprpsData:"+(j + 1));
                dataFileHeader.generateprpsData(dataFileHeader,currentPath+"//rixindljf//"+"zjrxDLJF" + ((deviceaddr-1)*PointCount + Pointaddr) + "_MONT_SPDC1_22_" + Acqtime + ".dat");
                dataFileHeader.generateprpsData(dataFileHeader,currentPath+"//rixindljfbackup//"+"zjrxDLJF" + ((deviceaddr-1)*PointCount + Pointaddr) + "_MONT_SPDC1_22_" + Acqtime + ".dat");
            
           // }
  
        }
    } catch (Exception e) {
        e.printStackTrace();

    } 
    }
    public static float parseHex88(String num) {
        int ret = Integer.parseInt(num, 16);
        if (num.length() == 2) {
            return ret;
        } else if (num.length() == 4) {
            ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
            return ret;
        } else {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
    }

    @Async("threadPool")
    public void startReceiveComThread(String str) {
        socketConnectType = 1;// 短连接
        isrecv.put(Thread.currentThread().getId(), true);
        // while (isrecv.get(Thread.currentThread().getId()) != null) {
        // recvSum("");
        recv(str);
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // }
    }

}
